package Student_Course;

import Main.UserLogin;

import java.sql.*;
import java.util.Scanner;

public class CourseSelection {
    public static void add() throws Exception {
        // 1. 加载 JDBC 驱动
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        // 2. 获取数据库连接
        String url = "jdbc:sqlserver://localhost:1433;databaseName=Student_Grade_Management_System;trustServerCertificate=true";
        String user = "ysy";
        String password = "051018";
        Connection conn = null;
        PreparedStatement ps1 = null, ps2 = null, ps3 = null;
        ResultSet rs = null, courseInfo = null, existingCourse = null, countResult = null;
        String courseId = "", courseName = "", Tname = "", userId = "";
        Scanner scan = new Scanner(System.in);
        try {
            conn = DriverManager.getConnection(url, user, password);

            // 模拟用户登录获取学号，这里假设UserLogin类有正确的定义和获取学号的逻辑
            userId = UserLogin.getUserId();

            // 查询学生选课操作界面中的课程信息
            String sql1 = "SELECT 课程编号, 课程名, 平时成绩占比, 考试成绩占比, 教师姓名 FROM 学生选课操作界面";

            // 4. 获取 Statement 对象，此处可以复用Statement对象，减少创建次数，提升性能
            Statement stmt = conn.createStatement();

            // 5. 执行 SQL 查询
            rs = stmt.executeQuery(sql1);

            // 6. 打印列名
            System.out.println("课程编号\t课程名\t平时成绩占比\t考试成绩占比\t教师姓名");
            System.out.println("==============================================");

            // 7. 打印数据
            while (rs.next()) {
                String courseIdFromDB = rs.getString("课程编号");
                String courseNameFromDB = rs.getString("课程名");
                String classWorkWeight = rs.getString("平时成绩占比");
                String examWeight = rs.getString("考试成绩占比");
                String TnameFromDB = rs.getString("教师姓名");

                // 打印课程信息
                System.out.printf("%s\t%s\t%s\t%s\t%s\n", courseIdFromDB, courseNameFromDB, classWorkWeight, examWeight, TnameFromDB);
            }

            while (true) {
                // 先检查学生已选课程数量
                String checkSql = "SELECT COUNT(*) FROM 选课信息 WHERE 学号 =?";
                ps3 = conn.prepareStatement(checkSql);
                ps3.setString(1, userId);
                countResult = ps3.executeQuery();
                int selectedCoursesCount = 0;
                if (countResult.next()) {
                    selectedCoursesCount = countResult.getInt(1); // 获取当前已选课程的数量
                }

                // 判断是否已达到选课限制
                if (selectedCoursesCount >= 8) {
                    System.out.println("您已选满8门课程，不能继续选课！");
                    break; // 跳出循环
                } else if (selectedCoursesCount >= 3) {
                    // 如果已选3门及以上课程，询问是否继续选课
                    System.out.print("您已选了 " + selectedCoursesCount + " 门课程，是否继续选课 (Y/N)? ");
                    String userChoice = scan.nextLine();
                    if (userChoice.equalsIgnoreCase("N")) {
                        System.out.println("您选择停止选课。");
                        break; // 跳出循环
                    }
                }

                // 复用之前的Statement对象stmt来执行查询课程信息，无需重新创建Statement
                rs = stmt.executeQuery(sql1);

                // 打印列名（可复用之前的打印代码逻辑）
                System.out.println("课程编号\t课程名\t平时成绩占比\t考试成绩占比\t教师姓名");
                System.out.println("==============================================");

                // 打印所有课程信息
                while (rs.next()) {
                    String courseIdFromDB = rs.getString("课程编号");
                    String courseNameFromDB = rs.getString("课程名");
                    String classWorkWeight = rs.getString("平时成绩占比");
                    String examWeight = rs.getString("考试成绩占比");
                    String TnameFromDB = rs.getString("教师姓名");

                    // 打印课程信息
                    System.out.printf("%s\t%s\t%s\t%s\t%s\n", courseIdFromDB, courseNameFromDB, classWorkWeight, examWeight, TnameFromDB);
                }

                // 获取用户输入的课程编号和教师姓名
                System.out.print("\n请输入你要选择的课程编号: ");
                courseId = scan.nextLine();
                System.out.print("\n请输入你要选择的教师姓名: ");
                Tname = scan.nextLine();

                // 查询课程是否存在
                String sql2 = "SELECT 课程名 FROM 学生选课操作界面 WHERE 课程编号 =? AND 教师姓名 =?";
                ps2 = conn.prepareStatement(sql2);
                ps2.setString(1, courseId);
                ps2.setString(2, Tname);
                courseInfo = ps2.executeQuery();
                if (!courseInfo.next()) {
                    System.out.println("没有找到该课程，请确认课程编号和教师姓名是否正确！");
                    continue; // 继续循环，重新选择课程
                }
                courseName = courseInfo.getString("课程名");

                // 查询该学生是否已选择该课程
                String checkCourseSql = "SELECT * FROM 选课信息 WHERE 学号 =? AND 课程编号 =?";
                ps3 = conn.prepareStatement(checkCourseSql);
                ps3.setString(1, userId);
                ps3.setString(2, courseId);
                existingCourse = ps3.executeQuery();

                if (existingCourse.next()) {
                    System.out.println("您已选择该课程，请不要重复选课！");
                } else {
                    // 插入选课信息
                    String sqlInsert = "INSERT INTO 选课信息 (学号, 课程编号, 课程名, 教师姓名) VALUES (?,?,?,?)";
                    ps3 = conn.prepareStatement(sqlInsert);
                    ps3.setString(1, userId);
                    ps3.setString(2, courseId);
                    ps3.setString(3, courseName);
                    ps3.setString(4, Tname);

                    int count = ps3.executeUpdate();
                    if (count > 0) {
                        System.out.println("选课成功！");
                    } else {
                        System.out.println("选课失败！");
                    }
                }

                // 判断是否继续选课
                System.out.print("\n是否继续选课 (Y/N)? ");
                String continueChoice = scan.nextLine();
                if (continueChoice.equalsIgnoreCase("N")) {
                    System.out.println("您选择停止选课。");
                    break; // 跳出循环
                }
            }
        } catch (SQLException e) {
            // 此处可以改为更友好的错误提示方式，例如记录日志并给用户一个通用的提示信息
            System.err.println("数据库操作出现异常，请稍后再试！");
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (rs!= null) rs.close();
                if (courseInfo!= null) courseInfo.close();
                if (existingCourse!= null) existingCourse.close();
                if (countResult!= null) countResult.close();
                if (ps1!= null) ps1.close();
                if (ps2!= null) ps2.close();
                if (ps3!= null) ps3.close();
                if (conn!= null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

